<template>
  <view class="container">
    <!-- Header with title and add button -->
    <view class="header">
      <uni-button type="primary" size="mini" @click="openAddPopup(null)">新增一级分类</uni-button>
    </view>

    <!-- Column Titles -->
    <view class="column-titles">
      <text class="name-title">分类名称</text>
      <text class="description-title">描述</text>
      <text class="action-title">操作</text>
    </view>
    <view class="" style="width: 100%;height: 1px;background-color: darkgray;"></view>

    <!-- Categories list with collapsible items -->
    <uni-collapse v-model="activeNames" accordion>
      <uni-collapse-item v-for="category in categories" :key="category.id" :name="String(category.id)">
        <template v-slot:title>
          <view class="category-item">
            <text class="name">{{ category.name }}</text>
            <text class="description">{{ category.description }}</text>
            <view class="actions">
              <uni-button type="primary" size="mini" @click.stop="openAddPopup(category)">添加二级分类</uni-button>
              <uni-button type="default" size="mini" @click.stop="openEditPopup(category)">编辑</uni-button>
              <uni-button type="error" size="mini" @click.stop="openDeletePopup(category, null)">删除</uni-button>
            </view>
          </view>
        </template>
        <view class="subcategory-list">
          <hr style="border: none; border-top: 1px dashed darkgray;width: 90%; margin-left:50px;">
          <view v-for="subCategory in category.subcategories" :key="subCategory.id" class="sub-category">
            <text class="name">{{ subCategory.name }}</text>
            <text class="description">{{ subCategory.description }}</text>
            <view class="actions">
              <uni-button type="default" size="mini" @click.stop="openEditPopup(subCategory, category)">编辑</uni-button>
              <uni-button type="error" size="mini" @click.stop="openDeletePopup(subCategory, category)">删除</uni-button>
            </view>
          </view>
        </view>
      </uni-collapse-item>
    </uni-collapse>

    <!-- Popup for Adding and Editing Categories -->
    <uni-popup ref="editPopup" type="center">
      <view class="popup-container">
        <h3 v-if="currentCategory && !currentParent">{{ currentCategory.id ? '编辑分类' : '新增一级分类' }}</h3>
        <h3 v-if="currentParent">新增二级分类到 {{ currentParent.name }}</h3>
        <view class="form-row">
          <label>分类名称：</label>
          <input v-model="currentCategory.name" class="input-field" />
        </view>
        <view class="form-row">
          <label>描述：</label>
          <input v-model="currentCategory.description" class="input-field" />
        </view>
        <view class="button-group">
          <uni-button type="modal-button save" size="mini" @click="saveCategory">保存</uni-button>
          <uni-button type="modal-button cancel" size="mini" @click="closePopup">取消</uni-button>
        </view>
      </view>
    </uni-popup>

    <!-- Popup for Confirmation on Deletion -->
    <uni-popup ref="deletePopup" type="center">
      <view class="popup-container">
        <h3>确认删除</h3>
        <text>确定要删除 "{{ currentCategory.name }}" 吗？</text>
        <view class="button-group">
          <uni-button type="modal-button delete" size="small" @click="confirmDelete">删除</uni-button>
          <uni-button type="modal-button cancel" size="small" @click="closePopup">取消</uni-button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      categories: [], // 一级分类列表
      currentCategory: {}, // 当前操作的分类
      currentParent: null, // 当前操作的父级分类
      activeNames: [], // 展开的分类项
      userInfo: {} // 用户信息
    };
  },
  methods: {
    // 打开新增或编辑分类弹窗
    openAddPopup(parent) {
      this.currentCategory = { name: '', description: '' };
      this.currentParent = parent;
      this.$refs.editPopup.open();
    },
    openEditPopup(category, parent) {
      this.currentCategory = Object.assign({}, category);
      this.currentParent = parent;
      this.$refs.editPopup.open();
    },
    // 关闭弹窗
    closePopup() {
      this.$refs.editPopup.close();
      this.$refs.deletePopup.close();
    },
    // 保存分类
    async saveCategory() {
    const categoryData = {
        name: this.currentCategory.name,
        description: this.currentCategory.description,
        parent_id: this.currentParent ? this.currentParent.id : 0,
        main_account_id: this.userInfo.user_id  // 确保传递 main_account_id
    };

    if (this.currentCategory.id) {
        categoryData.id = this.currentCategory.id;
    }

    const res = await this.$myRuquest({
        url: '/index/plugin.users/saveCategory',
        method: 'POST',
        data: categoryData
    }).then(res => {
        if (res.data.code === 200) {
            uni.showToast({
                title: '操作成功',
                icon: 'success',
                duration: 2000
            });
            this.fetchCategories();
            this.closePopup();
        } else {
            uni.showToast({
                title: res.data.message,
                icon: 'none',
                duration: 2000
            });
        }
    }).catch(() => {
        uni.showToast({
            title: '保存分类失败',
            icon: 'none',
            duration: 2000
        });
    });
},

    // 打开删除确认弹窗
    openDeletePopup(category, parent) {
      this.currentCategory = category;
      this.currentParent = parent;
      this.$refs.deletePopup.open();
    },
    // 确认删除分类
    async confirmDelete() {
      const res = await this.$myRuquest({
        url: '/index/plugin.users/deleteCategory',
        method: 'POST',
        data: {
          id: this.currentCategory.id,
          main_account_id: this.userInfo.user_id
        }
      });
      if (res.data.code === 200) {
        uni.showToast({
          title: '删除成功',
          icon: 'success',
          duration: 2000
        });
        this.fetchCategories();
        this.closePopup();
      } else {
        uni.showToast({
          title: res.data.message,
          icon: 'none',
          duration: 2000
        });
      }
    },
    // 获取分类列表
    async fetchCategories() {
      const res = await this.$myRuquest({
        url: '/index/plugin.users/getCategories',
        method: 'GET',
        data: {
          main_account_id: this.userInfo.user_id
        }
      });
      if (res.data.code === 200) {
        this.categories = res.data.data;
      } else {
        uni.showToast({
          title: res.data.message,
          icon: 'none',
          duration: 2000
        });
      }
    },
    // 检查是否登录
    checkLoginStatus() {
      const token = uni.getStorageSync('token');
      if (token) {
        this.userInfo = JSON.parse(uni.getStorageSync('userInfo'));
      } else {
        this.userInfo = {};
        this.$router.push('/pages/login/login');
      }
    }
  },
  mounted() {
    this.checkLoginStatus();
    this.fetchCategories();
  }
};
</script>

<style scoped>
.container {
  padding: 20px;
  background-color: #ecf0f1;
}

.header {
}

.popup-container {
  width: 80%;
  max-width: 500px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.button-group {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.title {
  font-size: 20px;
  font-weight: bold;
}

.column-titles {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  padding: 10px;
  font-weight: bold;
}

.modal-button {
  flex: 1;
  padding: 10px 15px;
  margin: 0 5px;
  background-color: #1abc9c;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.form-row {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

h3 {
  margin-bottom: 20px;
  text-align: center;
  color: #333;
}

label {
  width: 80px;
  color: #666;
  margin-right: 10px;
}

.input-field {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  outline: none;
}

.button-group {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.modal-button.save:hover {
  background-color: #16a085;
}

.modal-button.delete {
  background-color: #e74c3c;
}

.modal-button.delete:hover {
  background-color: #c0392b;
}

.modal-button.cancel {
  background-color: #95a5a6;
}

.modal-button.cancel:hover {
  background-color: #7f8c8d;
}

.category-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  background-color: #fff;
}

.sub-category {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  margin-right: 40px;
  margin-left: 40px;
}

.name-title, .description-title, .action-title, .name, .description {
  flex: 1;
  text-align: center;
}

.action-title {
  flex: 0.8;
}

.actions {
  display: flex;
  gap: 10px;
  justify-content: center;
  margin-right: 10px;
}

.sub-category {
  background-color: #fff;
  border-bottom: 1px solid #ddd;
}
</style>
